package servlet.personage;

import data.Insert;
import data.Select;
import data.Updata;
import file.FileManage;
import servlet.Control;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

import static file.FileManage.REALPATH;

@WebServlet(name = "UploadImg",value = "/personage/uploadImg")
@MultipartConfig(location = "/home/v/temp",maxFileSize = 1024*1024*1)
public class UploadImg extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        //获取id
        Part partId=request.getPart("id");
        int id= Integer.parseInt(new Scanner(partId.getInputStream()).next());
        String path="/user/"+id+"/";

        FileManage.initDir(REALPATH+path);

        //获取上传的文件
        Part part=request.getPart("file");
        if(part.getSize()<1024*1024*1){
            long time=System.currentTimeMillis();
            path=path+time;

            String oldPath=Select.profilePicture(id);
            //写入文件
            if(Updata.changProfileImg(id+"",path)){
                part.write(REALPATH+path);
                Control.success(response);

                //删除旧的文件
                File file=new File(REALPATH+oldPath);
                file.delete();
                return;
            }
        }


        Control.fail(response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    private static void initDir(String path){
        File file=new File(path);
        if(!file.exists()){
            file.mkdir();
        }
    }
}
